package com.wenzhoujie.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.lingou.www.R.color;
import com.sunday.eventbus.SDBaseEvent;
import com.wenzhoujie.HomeSearchActivity;
import com.wenzhoujie.MainActivity;
import com.wenzhoujie.adapter.CategoryCateLeftAdapter;
import com.wenzhoujie.adapter.CategoryCateRightAdapter;
import com.wenzhoujie.adapter.CategoryCityListAdapter;
import com.wenzhoujie.adapter.CategoryOrderAdapter;
import com.wenzhoujie.adapter.ECshopListAdapter;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.constant.Constant.CategoryOrderTypeName;
import com.wenzhoujie.constant.Constant.CategoryOrderTypeValue;
import com.wenzhoujie.constant.Constant.SearchTypeNormal;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.customview.SD2LvCategoryView;
import com.wenzhoujie.customview.SDBottomNavigatorBaseItem;
import com.wenzhoujie.customview.SDLvCategoryView;
import com.wenzhoujie.customview.SDLvCategoryView.SDLvCategoryViewListener;
import com.wenzhoujie.event.EnumEventTag;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.library.title.SDTitleTwoRightButton.SDTitleTwoRightButtonListener;
import com.wenzhoujie.library.utils.SDToast;
import com.wenzhoujie.library.utils.SDViewUtil;
import com.wenzhoujie.model.Bcate_listBcate_typeModel;
import com.wenzhoujie.model.Bcate_listModel;
import com.wenzhoujie.model.CategoryOrderModel;
import com.wenzhoujie.model.ECshoplistActItemModel;
import com.wenzhoujie.model.Quan_listModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.act.ECshoplistActModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDViewNavigatorManager;
import com.wenzhoujie.utils.ViewInject;
import com.wenzhoujie.work.AppRuntimeWorker;

public class ECshopListFragment extends BaseFragment implements OnClickListener
{
	public static final String EXTRA_TITLE_TXT = "extra_title_txt";
	public static final String EXTRA_CATE_NAME = "extra_cate_name";
	/** key */
	public static String EXTRA_KEY_WORD = "extra_key_word";

	/** 大分类id */
	public static final String EXTRA_CATE_ID = "extra_cate_id";

	/** 小分类id */
	public static final String EXTRA_CATA_TYPE_ID = "extra_cata_type_id";

	/** 商家id */
	public static final String EXTRA_MERCHANT_ID = "extra_merchant_id";

	@ViewInject(id = R.id.frag_ecshop_list_cv_left)
	private SD2LvCategoryView mCvLeft = null;

	@ViewInject(id = R.id.frag_ecshop_list_cv_middle)
	private SDLvCategoryView mCvMiddle = null;

	@ViewInject(id = R.id.frag_ecshop_list_cv_right)
	private SDLvCategoryView mCvRight = null;

	@ViewInject(id = R.id.frag_ecshop_list_ll_empty)
	private LinearLayout mLlEmpty = null;

	@ViewInject(id = R.id.frag_ecshop_list_ll_current_search)
	private LinearLayout mLlCurrentSearch = null;

	@ViewInject(id = R.id.frag_ecshop_list_tv_current_keyword)
	private TextView mTvCurrentKeyword = null;

	@ViewInject(id = R.id.frag_ecshop_list_ptrlv_content)
	private PullToRefreshListView mPtrlvContent = null;

	private ECshopListAdapter mAdapter = null;
	private List<ECshoplistActItemModel> mListModel = new ArrayList<ECshoplistActItemModel>();

	private SDViewNavigatorManager mViewManager = new SDViewNavigatorManager();

	private boolean isFirstBindCategoryViewData = true;

	private int pageTotal;
	// ===============提交服务器参数
	private String catalog_id;// 商品分类ID
	private String cata_type_id;// 商品二级分类
	private int city_id;// 城市分类ID
	private String quan_id;// 商圈id
	private int page;// 分页
	private String keyword;// 关键字
	private String city_name;// 城市名称
	private String order_type; // 排序类型
	private String merchant_id; // 商家id

	private String title_txt;
	private String cata_type_name;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.frag_ecshop_list, container, false);
		view = setmTitleType(TitleType.TITLE_TWO_RIGHT_BUTTON, view);
		IocUtil.initInjectedView(this, view);
		init();
		return view;
	}

	private void init()
	{
		getIntentData();
		initTitle();
		bindDefaultLvData();
		initCategoryView();
		initCategoryViewNavigatorManager();
		registeClick();
		initPullRefreshLv();
	}

	private void initTitle()
	{
		mTitleTwoRightBtns.setmListener(new SDTitleTwoRightButtonListener()
		{

			@Override
			public void onRightButton2CLick_SDTitleTwoRightButton(View v)
			{
				Intent intent = new Intent(getActivity(), HomeSearchActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.putExtra(HomeSearchActivity.EXTRA_SEARCH_TYPE, SearchTypeNormal.SHOP);
				startActivity(intent);
			}

			@Override
			public void onRightButton1CLick_SDTitleTwoRightButton(View v)
			{
			}

			@Override
			public void onLeftButtonCLick_SDTitleTwoRightButton(View v)
			{
				if (getActivity() instanceof MainActivity)
				{
				} else
				{
					getActivity().finish();
				}
			}
		});

		if (getActivity() instanceof MainActivity)
		{
		} else
		{
			mTitleTwoRightBtns.setLeftImage(R.drawable.ic_arrow_left_back);
		}
		mTitleTwoRightBtns.setRightImage2(R.drawable.ic_search_home_top);

		String city = AppRuntimeWorker.getCity_name();

		if (title_txt != null)
		{
			mTitleTwoRightBtns.setTitleTop(title_txt + " - " + city);
		}
		else
		{
			if (!TextUtils.isEmpty(city))
			{
				mTitleTwoRightBtns.setTitleTop("商城" + " - " + city);
			} else
			{
				mTitleTwoRightBtns.setTitleTop("商城");
			}
		}
	}

	private void getIntentData()
	{
		keyword = getActivity().getIntent().getStringExtra(EXTRA_KEY_WORD);
		catalog_id = getActivity().getIntent().getStringExtra(EXTRA_CATE_ID);
		cata_type_id = getActivity().getIntent().getStringExtra(EXTRA_CATA_TYPE_ID);
		merchant_id = getActivity().getIntent().getStringExtra(EXTRA_MERCHANT_ID);
		title_txt = getActivity().getIntent().getStringExtra(EXTRA_TITLE_TXT);
		cata_type_name = getActivity().getIntent().getStringExtra(EXTRA_CATE_NAME);

		if (AppHelper.isEmptyString(keyword))
		{
			mLlCurrentSearch.setVisibility(View.GONE);
		} else
		{
			mLlCurrentSearch.setVisibility(View.VISIBLE);
			mTvCurrentKeyword.setText(keyword);
		}

	}

	private void initPullRefreshLv()
	{
		mPtrlvContent.setMode(Mode.BOTH);
		mPtrlvContent.setOnRefreshListener(new OnRefreshListener2<ListView>()
		{

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView)
			{
				page = 1;
				requestData(false);
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView)
			{
				page++;
				if (page > pageTotal && pageTotal > 0)
				{
					SDToast.showToast("没有更多数据了");
					mPtrlvContent.onRefreshComplete();
				} else
				{
					requestData(true);
				}
			}
		});
		mPtrlvContent.setRefreshing();
	}

	private void bindDefaultLvData()
	{
		mAdapter = new ECshopListAdapter(mListModel, getActivity());
		mPtrlvContent.setAdapter(mAdapter);
	}

	private void initCategoryViewNavigatorManager()
	{
		SDBottomNavigatorBaseItem[] items = new SDBottomNavigatorBaseItem[] { mCvLeft, mCvMiddle, mCvRight };
		mViewManager.setItems(items);
		mViewManager.setmMode(SDViewNavigatorManager.Mode.CAN_NONE_SELECT);
	}

	private void initCategoryView()
	{

		// 左边分类view
		mCvLeft.setmBackgroundNormal(R.drawable.bg_choosebar_press_down);
		mCvLeft.setmBackgroundSelect(R.drawable.bg_choosebar_press_up);
		mCvLeft.setmTextColorNormal(getResources().getColor(color.text_home_item_content));
		mCvLeft.setmTextColorSelect(getResources().getColor(color.main_color));
		mCvLeft.setmListener(new SD2LvCategoryView.SD2LvCategoryViewListener()
		{

			@Override
			public void onRightItemSelect(int leftIndex, int rightIndex, Object leftModel, Object rightModel)
			{
				Bcate_listModel left = (Bcate_listModel) leftModel;
				Bcate_listBcate_typeModel right = (Bcate_listBcate_typeModel) rightModel;
				catalog_id = left.getId();
				cata_type_id = right.getId();
				mPtrlvContent.setRefreshing();
				cata_type_name = null;
			}

			@Override
			public void onLeftItemSelect(int leftIndex, Object leftModel, boolean isNotifyDirect)
			{
				if (isNotifyDirect)
				{
					Bcate_listModel left = (Bcate_listModel) leftModel;
					Bcate_listBcate_typeModel right = left.getBcate_type().get(0);
					catalog_id = left.getId();
					cata_type_id = right.getId();
					mPtrlvContent.setRefreshing();
					cata_type_name = null;
				}
			}
		});

		// 中间分类view
		mCvMiddle.setmBackgroundNormal(R.drawable.bg_choosebar_press_down_2);
		mCvMiddle.setmBackgroundSelect(R.drawable.bg_choosebar_press_up_2);
		mCvMiddle.setmTextColorNormal(getResources().getColor(color.text_home_item_content));
		mCvMiddle.setmTextColorSelect(getResources().getColor(color.main_color));
		mCvMiddle.setmListener(new SDLvCategoryViewListener()
		{
			@Override
			public void onItemSelect(int index, Object model)
			{
				Quan_listModel quanListModel = (Quan_listModel) model;
				city_id = quanListModel.getCity_id();
				mPtrlvContent.setRefreshing();
			}
		});

		// 右边分类view
		mCvRight.setmBackgroundNormal(R.drawable.bg_choosebar_press_down_3);
		mCvRight.setmBackgroundSelect(R.drawable.bg_choosebar_press_up_3);
		mCvRight.setmTextColorNormal(getResources().getColor(color.text_home_item_content));
		mCvRight.setmTextColorSelect(getResources().getColor(color.main_color));
		mCvRight.setmListener(new SDLvCategoryViewListener()
		{
			@Override
			public void onItemSelect(int index, Object model)
			{
				if (model instanceof CategoryOrderModel)
				{
					CategoryOrderModel orderModel = (CategoryOrderModel) model;
					order_type = orderModel.getValue();
					mPtrlvContent.setRefreshing();
				}
			}
		});

		List<CategoryOrderModel> listOrderModel = new ArrayList<CategoryOrderModel>();
		CategoryOrderModel orderModelDefault = new CategoryOrderModel();
		orderModelDefault.setName(CategoryOrderTypeName.DEFAULT);
		orderModelDefault.setValue(CategoryOrderTypeValue.DEFAULT);
		listOrderModel.add(orderModelDefault);

		CategoryOrderModel orderModelPoint = new CategoryOrderModel();
		orderModelPoint.setName(CategoryOrderTypeName.AVG_POINT);
		orderModelPoint.setValue(CategoryOrderTypeValue.AVG_POINT);
		listOrderModel.add(orderModelPoint);

		CategoryOrderModel orderModelNewest = new CategoryOrderModel();
		orderModelNewest.setName(CategoryOrderTypeName.NEWEST);
		orderModelNewest.setValue(CategoryOrderTypeValue.NEWEST);
		listOrderModel.add(orderModelNewest);

		CategoryOrderModel orderModelBuyCount = new CategoryOrderModel();
		orderModelBuyCount.setName(CategoryOrderTypeName.BUY_COUNT);
		orderModelBuyCount.setValue(CategoryOrderTypeValue.BUY_COUNT);
		listOrderModel.add(orderModelBuyCount);

		CategoryOrderModel orderModelPriceAsc = new CategoryOrderModel();
		orderModelPriceAsc.setName(CategoryOrderTypeName.PRICE_ASC);
		orderModelPriceAsc.setValue(CategoryOrderTypeValue.PRICE_ASC);
		listOrderModel.add(orderModelPriceAsc);

		CategoryOrderModel orderModelPriceDesc = new CategoryOrderModel();
		orderModelPriceDesc.setName(CategoryOrderTypeName.PRICE_DESC);
		orderModelPriceDesc.setValue(CategoryOrderTypeValue.PRICE_DESC);
		listOrderModel.add(orderModelPriceDesc);

		CategoryOrderAdapter adapter = new CategoryOrderAdapter(listOrderModel, getActivity());
		mCvRight.setAdapter(adapter);

	}

	/**
	 * 请求商品列表接口
	 * 
	 * @param isLoadMore
	 */
	private void requestData(final boolean isLoadMore)
	{
		RequestModel model = new RequestModel();
		model.put("act", "goodslist");
		model.put("keyword", keyword);
		model.put("order_type", order_type); // 排序类型
		model.put("cata_type_id", cata_type_id);// 小分类ID
		model.put("catalog_id", catalog_id);// 大分类ID
		model.put("quan_id", quan_id); // 商圈
		model.put("city_id", AppRuntimeWorker.getCity_id());
		model.put("merchant_id", merchant_id);
		model.put("page", page);
		RequestCallBack<String> handler = new RequestCallBack<String>()
		{

			@Override
			public void onStart()
			{

			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				ECshoplistActModel actModel = JsonUtil.json2Object(responseInfo.result, ECshoplistActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel))
				{
					if (isFirstBindCategoryViewData)
					{
						bindLeftCategoryViewData(actModel.getBcate_list());
						bindMiddleCategoryViewData(actModel.getQuan_list());
						isFirstBindCategoryViewData = false;
					}

					if (actModel.getPage() != null)
					{
						page = actModel.getPage().getPage();
						pageTotal = actModel.getPage().getPage_total();
					}

					SDViewUtil.updateAdapterByList(mListModel, actModel.getItem(), mAdapter, isLoadMore);
				}
				if (cata_type_name != null)
				{
					mCvLeft.setTitle(cata_type_name);
				}
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{

			}

			@Override
			public void onFinish()
			{
				dealFinishRequest();
			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);

	}

	protected void dealFinishRequest()
	{
		mPtrlvContent.onRefreshComplete();
		SDViewUtil.toggleEmptyMsgByList(mListModel, mLlEmpty);
	}

	private void bindLeftCategoryViewData(List<Bcate_listModel> listModel)
	{
		if (listModel != null && listModel.size() > 0)
		{
			Bcate_listModel leftModel = listModel.get(0);
			if (leftModel != null)
			{
				List<Bcate_listBcate_typeModel> listRight = leftModel.getBcate_type();

				CategoryCateLeftAdapter adapterLeft = new CategoryCateLeftAdapter(listModel, getActivity());
				adapterLeft.setDefaultSelectId(catalog_id);
				CategoryCateRightAdapter adapterRight = new CategoryCateRightAdapter(listRight, getActivity());
				mCvLeft.setLeftAdapter(adapterLeft);
				mCvLeft.setRightAdapter(adapterRight);
				mCvLeft.setAdapterFinish();
			}
		}
	}

	private void bindMiddleCategoryViewData(List<Quan_listModel> listQuan)
	{
		CategoryCityListAdapter adapter = new CategoryCityListAdapter(listQuan, getActivity());
		mCvMiddle.setAdapter(adapter);
	}

	@Override
	public void onEventMainThread(SDBaseEvent event)
	{
		// TODO Auto-generated method stub
		super.onEventMainThread(event);
		switch (EnumEventTag.valueOf(event.getEventTagInt()))
		{
		case CITY_CHANGE:
			initTitle();
			city_id = AppRuntimeWorker.getCity_id();
			mPtrlvContent.setRefreshing();
			break;

		default:
			break;
		}
	}

	private void registeClick()
	{
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{

		default:
			break;
		}
	}

}